package com.hook.tools;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * Created by Administrator on 2018/3/26.
 *
 * @author QuJianJun
 */
public class HttpTools {
	/**
	 * 返回响应头信息
	 * @param url
	 * @return
	 */
	public static String GetHttpHeader(String url, String referer){
			String result = "";
			try {
				URL u = new URL(url);
				HttpURLConnection conn = (HttpURLConnection)u.openConnection();
				conn.setRequestMethod("GET"); 
				conn.addRequestProperty("Referer", referer);
				conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/600.1.3 (KHTML, like Gecko) Version/8.0 Mobile/12A4345d Safari/600.1.4");
				//必须设置false，否则会自动redirect到重定向后的地址 
	            conn.setInstanceFollowRedirects(false);
	            conn.connect();
	            if (conn.getResponseCode() == 302 || conn.getResponseCode() == 301) { 
	                //如果会重定向，保存302重定向地址，以及Cookies,然后重新发送请求(模拟请求)
	                result = conn.getHeaderField("Location"); 
	            //    Map<String, List<String>> map = conn.getHeaderFields();
	        //        for (String key : map.keySet()) {
	        //        	System.out.println(key+"    ----->"+ map.get(key));
	        //        }
	        //        GetHttpHeader(result,"");
	            }
	            
			} catch (Exception e) {
				e.printStackTrace();
			}
			return result;
	}
	
	/**
	 * 获取网站返回内容
	 * @param url
	 * @return
	 */
	public static String Getcode(String url, String encode, String referer, String cookie){
		if(encode==""){encode="UTF-8";}
		String result = "";
		String temp="";
		try {
			URL u = new URL(url);
			HttpURLConnection conn = (HttpURLConnection)u.openConnection();
			conn.setRequestProperty("Cookie", cookie);
			conn.setRequestProperty("Referer", referer);
			conn.setRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1");
			//连接远程服务器超时设置(毫秒)
			conn.setConnectTimeout(20000);
			//读取内容超时设置
			conn.setReadTimeout(20000);
            InputStreamReader isr = new InputStreamReader(conn.getInputStream(),encode);
            BufferedReader br = new BufferedReader(isr);
            while((temp = br.readLine()) != null){  
			result +=temp+"\n";
			}
           if (isr!=null) {
        	   isr.close();
           }
		} catch (Exception e) {
			System.out.println("***************************************************************异常地址:"+url);
			e.printStackTrace();
		}
		
		return result;
	}
	 /**
     * 向指定 URL 发送POST方法的请求
     *
     * @param url
     *            发送请求的 URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return 所代表远程资源的响应结果
     */
    public static String sendPost(String url, String param, Map<String, String> headerMap) {
		OutputStream out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection();
            // 设置通用的请求属性

			//header 头
			for(Map.Entry m : headerMap.entrySet()){
				conn.setRequestProperty(m.getKey().toString(),headerMap.get(m.getKey()));
			}
			conn.setConnectTimeout(3000);
			conn.setReadTimeout(3000);
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = conn.getOutputStream();
            // 发送请求参数
            out.write(param.getBytes("UTF-8"));
            // flush输出流的缓冲
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8"));
            String line;
            while ((line = in.readLine()) != null) {
                result += line+"\n";
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+"***************************异常地址:"+url+"异常参数:"+param);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }
	
}
